<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 6/5/24
 * Time: 3:59 PM
 */

namespace App\Console\Commands;

use App\Models\WechatAccount;
use App\Models\WechatCorp;
use App\Services\KfAccountService;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Console\Command;
use App\Models\WechatAccountChat as AcModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;


/**
 * 成员客户统计
 *
 * Class Push
 * @package App\Console\Commands
 */
class WechatAccountChat extends Command
{
    const REDIS_CORP_WECHAT_ACCOUNT_CHAT_NEXT_CURSOR = 'corp_wechat_account_chat_next_cursor_';


    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wechat:account_chat';


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '成员客户群统计';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     *
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        $corpIds = WechatCorp::query()->pluck('corp_id')->toArray();

        Log::info('同步成员客户群信息');
        foreach ($corpIds as $corpId) {
            $userIds = WechatAccount::query()->where('corp_id', $corpId)->pluck('user_id')->toArray();
            if (!$userIds) {
                continue;
            }
            foreach ($userIds as $userId) {
                $nextCursor = Cache::get(self::REDIS_CORP_WECHAT_ACCOUNT_CHAT_NEXT_CURSOR . $userId);
                $this->getChatList($corpId, $userId, $nextCursor);
            }
        }
    }


    public function getChatList($corpId, $userId, $nextCursor = '')
    {
        $client   = new Client();
        $service  = new KfAccountService();
        $bodyData = [
            'owner_filter' => [
                'userid_list' => [$userId]
            ],
            'limit'        => 100
        ];
        if ($nextCursor) {
            $bodyData['cursor'] = $nextCursor;
        }
        $body     = [
            'headers'            => $service->headers,
            RequestOptions::JSON => $bodyData
        ];
        $token    = $service->getReplaceAccessToken($corpId);
        $response = $client->request(
            'POST',
            sprintf($service->api['chat_list'], $token),
            $body
        );
        if ($response->getStatusCode() != 200) {

            return [];
        }
        $contents = $response->getBody()->getContents();
        $data     = json_decode($contents, true);
        if ($data['errcode'] != 0) {

            return [];
        }
        if (!$chatList = $data['group_chat_list'] ?? []) {

            return [];
        }
        foreach ($chatList as $item) {
            $ac         = AcModel::query()->firstOrNew(['corp_id' => $corpId, 'user_id' => $userId, 'chat_id' => $item['chat_id']]);
            $ac->status = $item['status'] ?? 0;
            $ac->save();
        }
        if ($nextCursor = $data['next_cursor'] ?? '') {
            Cache::set(self::REDIS_CORP_WECHAT_ACCOUNT_CHAT_NEXT_CURSOR . $userId, $nextCursor);
        }
    }
}
